import { IResColumnsOpt, IResourceRangeRightTable } from '../type';
import cls from 'classnames';
import { useContext, useMemo, useState } from 'react';
import { ResourcesContext } from '../hooks';
import { message, Table } from 'antd';
import { getResouColumns } from '../components/PageConfig';
import { ResourRangeContext } from '../hooks/useResourRangeContext';
import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import { ResourRangeAddModal } from './ResourRangeAddModal';
import { ConfirmModalRange } from './ConfirmModalRange';
import { useRequest } from 'umi';
import { switchResourIsOpen } from '../hooks/useResManageReq';
import { TableRowSelection } from 'antd/es/table/interface';

export const ResourceRangeRightTable: React.FC<IResourceRangeRightTable> = ({
  dataSource,
  tableLoading, //表格的loading
}) => {
  const { prefixCls, curRes } = useContext(ResourcesContext);
  const {
    searchTableValue,
    expandedRowKeys,
    resRangeDispatch,
    reloadTableDataSource,
    selectKeys,
    checkedRowKeys,
  } = useContext(ResourRangeContext);

  const [showRangeModal, setShowRangeModal] = useState<boolean>(); //是否打开新增弹框
  const [chilckRows, setChilckRows] = useState<any>(); //保存 编辑的数据
  const openRangeModal = (isFalse: boolean) => {
    setShowRangeModal(isFalse);
  };

  const [showConfimRangeModal, setShowConfimRangeModal] = useState<boolean>(
    false,
  ); //是否打开 提示框modal
  const openConfimRange = (isFalse: boolean) => {
    setShowConfimRangeModal(isFalse);
  };

  // 表格操作方法
  const onPosOptClick: IResColumnsOpt = {
    onEditAdd: (record) => {
      setChilckRows(record);
      openRangeModal(true);
    },
    onChangeIsOpen: (checked, record) => {
      if (checked) {
        if (record?.pIsOpen == 1) {
          checkFalseIsOpen?.run(checked, record);
        } else {
          openConfimRange(true);
        }
      } else {
        openConfimRange(true);
      }
    },
  };

  // const [showColumns, setShowColumns] = useState(getResouColumns(curRes, onPosOptClick, searchTableValue));
  // let showColumns = getResouColumns(curRes, onPosOptClick, searchTableValue);

  /** 表格行配置 */
  const columnsImtes = useMemo(() => {
    return getResouColumns(curRes, onPosOptClick, searchTableValue);
  }, [curRes, searchTableValue]);

  // useEffect(() => {
  //   let columns = useState(getResouColumns(curRes, onPosOptClick, searchTableValue));
  //   setShowColumns(columns)
  // }, [expandedRowKeys])

  // 修改下拉展开图标
  const expandIcon = (props: any) => {
    if (props.record.children && props.record.children.length > 0) {
      if (props.expanded) {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretDownOutlined />
            </span>
          </span>
        );
      } else {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretRightOutlined />
            </span>
          </span>
        );
      }
    } else {
      return (
        <span
          style={{
            float: 'left',
            marginRight: '5px',
          }}
        >
          <span style={{ fontSize: '10px', visibility: 'hidden' }}>
            <CaretRightOutlined />
          </span>
        </span>
      );
    }
  };

  // 表格行点击选中改变方法
  const tableChange = (selectedRowKeys: any, selectedRows: any) => {
    if (!selectedRows?.[0]?.url && selectedRows?.[0]?.method == 'ALL') {
      resRangeDispatch({
        type: 'range-checkedRowKeys',
        payload: selectedRowKeys,
      });
    } else {
      resRangeDispatch({
        type: 'range-checkedRowKeys',
        payload: [],
      });
    }
    resRangeDispatch({
      type: 'range-checkTableRows',
      payload: selectedRows?.[0],
    });
    setChilckRows(selectedRows?.[0]);
  };

  // 禁用资源
  const chanageSwitch = (check: boolean, resObj: any) => {
    checkFalseIsOpen?.run(check, resObj);
  };

  // 调用修改状态的按钮
  const checkFalseIsOpen = useRequest(
    (openState: boolean, recObj: any) => {
      let params = {
        versionNum: recObj?.versionNum,
        id: recObj?.id,
        isOpen: openState ? 1 : 0,
      };
      return switchResourIsOpen(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          reloadTableDataSource(selectKeys?.[0]);
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  /** 表格分页 */
  const rowSelection = useMemo(() => {
    return {
      type: 'radio',
      selectedRowKeys: checkedRowKeys,
      onChange: tableChange,
      getCheckboxProps: (record: any) => {
        if (!record?.url && record?.method == 'ALL') {
          return {
            disabled: false,
          };
        } else {
          return {
            disabled: true,
          };
        }
      },
    };
  }, [checkedRowKeys]);

  return (
    <>
      <div className={cls(prefixCls + 'table-content')}>
        <div className={cls('list-table')}>
          <Table
            size="small"
            columns={columnsImtes}
            bordered
            pagination={false}
            dataSource={dataSource}
            loading={tableLoading || checkFalseIsOpen?.loading}
            rowKey={(record) => record?.id}
            scroll={{ x: 1200, y: 'true' }}
            expandIcon={expandIcon}
            expandable={{
              onExpandedRowsChange: (keys: any) => {
                resRangeDispatch({
                  type: 'range-expandedRowKeys',
                  payloadS: keys,
                });
              },
              expandedRowKeys: expandedRowKeys,
            }}
            rowSelection={rowSelection as TableRowSelection<any>}
            onRow={(record) => {
              return {
                onClick: (event) => {
                  event.stopPropagation();
                  tableChange([record?.id], [record]);
                },
              };
            }}
          />
        </div>
      </div>

      {/* 新增编辑 弹框 */}
      {showRangeModal && (
        <ResourRangeAddModal
          onClose={() => {
            openRangeModal(false);
          }} //取消弹框
          pIdData={dataSource} //上级资源 pID字段数据源
          // editAddRows={{ detaID: expandedRowKeys?.length > 0 ? expandedRowKeys?.toString() : '' }}  //选中表格,默认为上级资源
          editAddRows={chilckRows} //选中数据
          visible={showRangeModal}
          modalType={'edit'}
        />
      )}

      {/* 是否打开提示框 */}
      {showConfimRangeModal && (
        <ConfirmModalRange
          visible={showConfimRangeModal}
          onClose={() => {
            openConfimRange(false);
          }}
          onReload={() => {
            reloadTableDataSource(selectKeys?.[0]);
          }}
          tableRowObj={chilckRows}
          chanageSwitch={chanageSwitch}
        />
      )}
    </>
  );
};
